package com.chao.yyks.util;


import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.chao.common.util.ListUtile;
import com.chao.common.util.StrUtile;
import com.chao.common.util.file.FileUpload;
import com.chao.yyks.modular.config.service.FdfsService;
import com.chao.yyks.modular.hearing.bean.EnHearing;
import com.chao.yyks.modular.hearing.mapper.EnHearingMapper;
import com.chao.yyks.modular.problem.bean.EnProblem;
import com.chao.yyks.modular.problem.bean.EnProblemAnswer;
import com.chao.yyks.modular.problem.mapper.EnProblemAnswerMapper;
import com.chao.yyks.util.webSocket.WebTtsWs2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 */
@Slf4j
@Component
@EnableScheduling
public class Tts2File {

    /**
     * 听力Mapper
     */
    @Autowired
    private EnHearingMapper enHearingMapper;

    /**
     * 问题答案Mapper
     */
    @Autowired
    private EnProblemAnswerMapper enProblemAnswerMapper;

    @Autowired
    private FdfsService fdfsService;

    private static final String apikey = "sk-4bc20a2a427e47e69aad73404b1954f7";

    private static final SpeechSynthesizer synthesizer = new SpeechSynthesizer();

    public static File toFileWas(String announcer,String msg) {
        WebTtsWs2.websocketWork37(Collections.singletonList(msg),announcer);
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new File(announcer+StrUtile.getMD5(msg)+".mp3");
    }


    /** * 每周周天晚上 7点到晚上11点 每间隔5分钟执行一次 每次执行 10条语音文本和30道题语音生成 */
//    @Scheduled(cron = "15 0/3 19-23 * * 0")
    @Scheduled(cron = "15 0/3 * * * ?")
    public void saveEnHearing() {
        log.info("开始生成语音文件");
        List<EnHearing> hearingList = enHearingMapper.selectEnHearingNotUrl();
        List<EnProblem> problemList = enHearingMapper.selectEnHearingProblemNotUrl();
        if(ListUtile.isEmpty(hearingList) && ListUtile.isEmpty(problemList)) {
           return;
        }
        Map<String, List<String>> msg = new HashMap<>();
        msg.put("咨询女声", new ArrayList<>()); //咨询女声
        msg.put("咨询女声38", new ArrayList<>()); //咨询女声
        msg.put("咨询女声39", new ArrayList<>()); //咨询女声
        msg.put("教育女声", new ArrayList<>()); //教育女声
        msg.put("教育女声38", new ArrayList<>()); //教育女声
        msg.put("教育女声39", new ArrayList<>()); //教育女声
        msg.put("客服男声", new ArrayList<>()); //客服男声
        msg.put("客服男声37", new ArrayList<>()); //客服男声
        msg.put("客服男声38", new ArrayList<>()); //客服男声
        List<EnHearing> newHearingList = new ArrayList<>();
        if(!ListUtile.isEmpty(hearingList)) {
            for (EnHearing hearing : hearingList) {
                if (StrUtile.isEmpty(hearing.getHearingTitle())) {
                    continue;
                }
                if (StrUtile.isEmpty(hearing.getAnnouncer())) {
                    hearing.setAnnouncer("教育女声"); // 默认声音 使用教育女声
                }
                // 对话 分别生成
                if ("1".equals(hearing.getHearingDialogue()) && !hearing.getHearingTitle().contains("Recording")) {
                    msg.get(hearing.getAnnouncer()).add(hearing.getHearingTitle());
                } else { // 非对话 逐句生成
                    List<EnHearing> ss = new ArrayList<>();
                    String text = hearing.getHearingTitle();
                    msg.get(hearing.getAnnouncer()).add(text);
                    if (!"1".equals(hearing.getProblemUpType())) { // 非听力题 不逐句拆分
                        continue;
                    }
                    String[] texts1 = text.split("\n");
                    for (String text1:texts1) {
                        List<String> texts = SpliteText.sq(text1);
                        if(texts.contains("Directions")){
                            texts = Arrays.asList(text1);
                        }
                        for (String t : texts) {
                            EnHearing hearing1 = new EnHearing();
                            hearing1.setUpHearingId(hearing.getHearingId());
                            hearing1.setHearingId(StrUtile.getId());
                            hearing1.setHearingTitle(t.trim());
                            hearing1.setHearingType("1");
                            hearing1.setHearingDialogue("2");
                            hearing1.setLabelId(hearing.getLabelId());
                            hearing1.setAnnouncer(hearing.getAnnouncer());
                            hearing1.setHearingSection(hearing.getHearingSection());
                            hearing1.setProblemDate(hearing.getProblemDate());
                            hearing1.setProblemUpType(hearing.getProblemUpType());
                            ss.add(hearing1);
                        }
                    }
                    if(ss.size() > 1){
                        for (EnHearing hearing1 :ss){
                            newHearingList.add(hearing1);
                            msg.get(hearing.getAnnouncer()).add(hearing1.getHearingTitle());
                        }
                    }
                }
            }
        }
        Map<String, List<String>> msg1 = new HashMap<>();
        msg1.put("咨询女声", new ArrayList<>()); //咨询女声
        msg1.put("咨询女声38", new ArrayList<>()); //咨询女声
        msg1.put("咨询女声39", new ArrayList<>()); //咨询女声
        msg1.put("教育女声", new ArrayList<>()); //教育女声
        msg1.put("教育女声38", new ArrayList<>()); //教育女声
        msg1.put("教育女声39", new ArrayList<>()); //教育女声
        msg1.put("客服男声", new ArrayList<>()); //客服男声
        msg1.put("客服男声37", new ArrayList<>()); //客服男声
        msg1.put("客服男声38", new ArrayList<>()); //客服男声
        List<EnHearing> nh = new ArrayList<>();
        Map<String, List<EnHearing>> hearingMap = hearingList.stream().collect(Collectors.groupingBy(h->h.getAnnouncer()+h.getHearingTitle()));
        Map<String, List<EnHearing>> newHearingMap = newHearingList.stream().collect(Collectors.groupingBy(h->h.getAnnouncer()+h.getHearingTitle()));
        log.info("开始上传上次生成的文件:");
        for (Map.Entry<String, List<String>> entry: msg.entrySet()){
            for (String str:entry.getValue()) {
                File file = new File(entry.getKey().replace("38","").replace("37","").replace("39","")+StrUtile.getMD5(str)+".mp3");
                if(!file.exists()){
                    msg1.get(entry.getKey()).add(str);
                    continue;
                }
                String url = null;
                if(file.length() > 5){
                    FileUpload fileUpload = fdfsService.uploadThisFile(file);
                    url = fileUpload.getFilePrefix()+fileUpload.getFileUrl();
                }
                if(newHearingMap.containsKey(entry.getKey()+str)){
                    List<EnHearing> list = newHearingMap.get(entry.getKey()+str);
                    for (EnHearing h:list){
                        h.setHearingUrl(url);
                        nh.add(h);
                    }
                }
                if(StrUtile.isEmpty(url)){
                    file.delete();
                    continue;
                }
                if(hearingMap.containsKey(entry.getKey()+str)){
                    List<EnHearing> list = hearingMap.get(entry.getKey()+str);
                    for (EnHearing h:list){
                        h.setHearingUrl(url);
                        enHearingMapper.updateEnHearingUrl(h);
                    }
                }
                file.delete();
            }
        }
        List<EnProblemAnswer> enProblemAnswerList = new ArrayList<>();
        List<String> problems = new ArrayList<>(); // 题目 统一使用教育女声
        if(!ListUtile.isEmpty(problemList)){
            for (EnProblem problem : problemList) {
                File file = new File("教育女声"+StrUtile.getMD5(problem.getProblemTitle())+".mp3");
                if(file.exists()){
                    if(file.length() < 5){
                        file.delete();
                        continue;
                    }
                    FileUpload fileUpload = fdfsService.uploadThisFile(file);
                    String url = fileUpload.getFilePrefix() + fileUpload.getFileUrl();
                    if (StrUtile.isEmpty(fileUpload.getFileUrl())) {
                        continue;
                    }
                    EnProblemAnswer answer = new EnProblemAnswer();
                    answer.setProblemId(problem.getProblemId());
                    answer.setProblemAnswerLong(url);
                    enProblemAnswerList.add(answer);
                    file.delete();
                    continue;
                }
                problems.add(problem.getProblemTitle());
            }
        }
        log.info("开始生成文件");
        WebTtsWs2.websocketWork35(msg1.get("咨询女声"),"咨询女声");//咨询女声
        WebTtsWs2.websocketWork38(msg1.get("咨询女声38"),"咨询女声");//咨询女声
        WebTtsWs2.websocketWork39(msg1.get("咨询女声39"),"咨询女声");//咨询女声
        WebTtsWs2.websocketWork35(msg1.get("教育女声"),"教育女声");//教育女声
        WebTtsWs2.websocketWork38(msg1.get("教育女声38"),"教育女声");//教育女声
        WebTtsWs2.websocketWork39(msg1.get("教育女声39"),"教育女声");//教育女声
        WebTtsWs2.websocketWork35(msg1.get("客服男声"),"客服男声");//客服男声
        WebTtsWs2.websocketWork37(msg1.get("客服男声37"),"客服男声");//客服男声
        WebTtsWs2.websocketWork38(msg1.get("客服男声38"),"客服男声");//客服男声
        WebTtsWs2.websocketWork35(problems,"教育女声");//教育女声

        if(!nh.isEmpty()){
            enHearingMapper.insertAllEnHearing(nh);
        }
        if(!enProblemAnswerList.isEmpty()){
            enProblemAnswerMapper.insertAllEnProblemAnswer(enProblemAnswerList);
        }
        log.info("上传结束结束");
    }

//    // 咨询女声
//    public static Map<String, File> SyncAudioDataBeth(List<String> msg) {
//        if(ListUtile.isEmpty(msg)){
//            return new HashMap<>();
//        }
//        Map<String, File> map = new HashMap<>();
//        for (String m : msg) {
//            File file = new File(StrUtile.getMD5(m) + ".wav");
//            if(file.exists()){
//                map.put("咨询女声"+m, file);
//                continue;
//            }
//            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
//                    .model("sambert-beth-v1")
//                    .text(m)
//                    .rate(0.8F)
//                    .sampleRate(48000)
//                    .format(SpeechSynthesisAudioFormat.WAV)
//                    .apiKey(apikey)
//                    .build();
//            // 调用call方法，传入param参数，获取合成音频
//            ByteBuffer audio = synthesizer.call(param);
//            try (FileOutputStream fos = new FileOutputStream(file)) {
//                fos.write(audio.array());
//            } catch (IOException e) {
//                log.error("语音<{}>文件生成失败:{}", m, e.getMessage());
//                if (!map.isEmpty()) {
//                    return map;
//                }
//            }
//            map.put("咨询女声"+m, file);
//        }
//        return map;
//    }
//
//    // 教育女声
//    public static Map<String, File> SyncAudioDataDonna(List<String> msg) {
//        if(ListUtile.isEmpty(msg)){
//            return new HashMap<>();
//        }
//        Map<String, File> map = new HashMap<>();
//        for (String m : msg) {
//            File file = new File(StrUtile.getMD5(m) + ".wav");
//            if(file.exists()){
//                map.put("教育女声"+m, file);
//                continue;
//            }
//            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
//                    .model("sambert-donna-v1")
//                    .text(m)
//                    .rate(0.9F)
//                    .sampleRate(48000)
//                    .format(SpeechSynthesisAudioFormat.WAV)
//                    .apiKey(apikey)
//                    .build();
//            // 调用call方法，传入param参数，获取合成音频
//            ByteBuffer audio = synthesizer.call(param);
//            try (FileOutputStream fos = new FileOutputStream(file)) {
//                fos.write(audio.array());
//            } catch (IOException e) {
//                log.error("语音<{}>文件生成失败:{}", m, e.getMessage());
//                if (!map.isEmpty()) {
//                    return map;
//                }
//            }
//            map.put("教育女声"+m, file);
//        }
//        return map;
//    }
//
//    // 客服男声
//    public static Map<String, File> SyncAudioDataBrian(List<String> msg) {
//        if(ListUtile.isEmpty(msg)){
//            return new HashMap<>();
//        }
//        Map<String, File> map = new HashMap<>();
//        for (String m : msg) {
//            File file = new File(StrUtile.getMD5(m) + ".wav");
//            if(file.exists()){
//                map.put("客服男声"+m, file);
//                continue;
//            }
//            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
//                    .model("sambert-brian-v1")
//                    .text(m)
//                    .rate(0.72F)
//                    .sampleRate(48000)
//                    .format(SpeechSynthesisAudioFormat.WAV)
//                    .apiKey(apikey)
//                    .build();
//            // 调用call方法，传入param参数，获取合成音频
//            ByteBuffer audio = synthesizer.call(param);
//            try (FileOutputStream fos = new FileOutputStream(file)) {
//                fos.write(audio.array());
//            } catch (IOException e) {
//                log.error("语音<{}>文件生成失败:{}", m, e.getMessage());
//                if (!map.isEmpty()) {
//                    return map;
//                }
//            }
//            map.put("客服男声"+m, file);
//        }
//        return map;
//    }

//    public static void main(String[] args) {
////        List<String> msg = Arrays.asList("News Report Two\n" +
////                "Chinese employers are racing to hire AI talent, offering substantial salaries to secure future business advantages. Recruitment platform Liepin reported a 321.7% year-on-year increase in AI-generated content (AIGC) job openings and a 947% surge in job seekers in Q1. Average annual salaries for AIGC roles hit 408,700 yuan ($57,045), often exceeding 500,000 yuan. Cities like Beijing, Shanghai, Shenzhen, and Hangzhou, home to tech giants Alibaba, Tencent, and ByteDance, lead in AI job opportunities. ByteDance's \"Top Seed\" program recruits PhD graduates for AI roles with competitive packages. Tesla CEO Elon Musk also raised salaries for AI engineers due to competition from US-based OpenAI. Experts predict continued demand for AI talent, driven by technological advancements. However, a skills gap remains, with estimates pointing to a shortage of about 4 million AI professionals by 2030. Employers seek candidates with comprehensive AI knowledge, teamwork skills, and ethical awareness. Young professionals are advised to stay abreast of AI trends and pursue interdisciplinary education.                         \nQuestions 1 and 2 are based on the news report you have just heard.");
//
//        List<String> msg = Arrays.asList("Young professionals are advised to stay abreast of AI trends and pursue interdisciplinary education.");
//        Map<String, File> outFile = SyncAudioDataBrian(msg);
//        log.info("语音文件生成结束,开始上传:{}",outFile.size());
////        for (Map.Entry<String, File> entry: outFile.entrySet()){
////            uploadThisFile(entry.getValue());
////        }
////
//////        for (String m:msg){
//////            System.out.println(m+"\t"+"http://47.98.247.29:8888/group1/default/20240920/"+StrUtile.getMD5(m)+".wav");
//////        }
//    }

//    public static void uploadThisFile(File file) {
//        String result = "";
//        String fileName = StrUtile.getMD5(file.getName())+".mp4";
//        try {
//            String fileType;
//            if (fileName.contains(".")) {
//                String[] s = fileName.split("\\.");
//                fileType = s[s.length - 1];
//            } else {
//                fileType = "sys";
//            }
//            InputStreamResource isr = new InputStreamResource(Files.newInputStream(file.toPath()), fileName);
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            params.put("path", "default/" + DateUtile.toymd());
//            params.put("output", "json");
//            String str = HttpUtil.post("https://service.sdkjf.cn/group1/upload", params);
//            JSONObject json = JSONObject.parseObject(str);
//            if (json.containsKey("path")) {
//                result = json.getString("path");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if(!StrUtile.isEmpty(result)){
//            System.out.println("https://service.sdkjf.cn"+result);
////            file.delete();
//        }
//    }
//
//    public static void main(String[] args) {
//        uploadThisFile(new File("E:\\4444.mp4"));
//    }
}